package com.rbac.admin.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * Security工具类（简化版）
 * 
 * @author RBAC-Admin
 * @since 2024-01-01
 */
public class SecurityUtils {

    /**
     * 获取当前用户ID
     */
    public static String getCurrentUserId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object userId = session.getAttribute("userId");
                    if (userId != null) {
                        return userId.toString();
                    }
                }
                
                // 从请求头获取用户ID（如果有JWT等认证方式）
                String userIdHeader = request.getHeader("X-User-Id");
                if (userIdHeader != null && !userIdHeader.isEmpty()) {
                    return userIdHeader;
                }
            }
            
            // 默认返回系统用户ID
            return "1";
        } catch (Exception e) {
            return "1";
        }
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object username = session.getAttribute("username");
                    if (username != null) {
                        return username.toString();
                    }
                }
                
                // 从请求头获取用户名（需要URL解码）
                String usernameHeader = request.getHeader("X-Username");
                if (usernameHeader != null && !usernameHeader.isEmpty()) {
                    try {
                        return URLDecoder.decode(usernameHeader, StandardCharsets.UTF_8);
                    } catch (Exception e) {
                        return usernameHeader; // 如果解码失败，返回原值
                    }
                }
            }
            
            // 默认返回admin
            return "admin";
        } catch (Exception e) {
            return "admin";
        }
    }

    /**
     * 获取当前用户真实姓名
     */
    public static String getCurrentUserRealName() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object realName = session.getAttribute("realName");
                    if (realName != null) {
                        return realName.toString();
                    }
                }
                
                // 从请求头获取真实姓名（需要URL解码）
                String realNameHeader = request.getHeader("X-Real-Name");
                if (realNameHeader != null && !realNameHeader.isEmpty()) {
                    try {
                        return URLDecoder.decode(realNameHeader, StandardCharsets.UTF_8);
                    } catch (Exception e) {
                        return realNameHeader; // 如果解码失败，返回原值
                    }
                }
            }
            
            // 默认返回管理员
            return "管理员";
        } catch (Exception e) {
            return "管理员";
        }
    }

    /**
     * 获取当前用户的角色ID
     */
    public static String getCurrentUserRoleId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object roleId = session.getAttribute("currentRoleId");
                    if (roleId != null) {
                        return roleId.toString();
                    }
                }
                
                // 从请求头获取角色ID
                String roleIdHeader = request.getHeader("X-Role-Id");
                if (roleIdHeader != null && !roleIdHeader.isEmpty()) {
                    return roleIdHeader;
                }
            }
            
            // 默认返回空
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户的角色名称
     */
    public static String getCurrentUserRoleName() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object roleName = session.getAttribute("currentRoleName");
                    if (roleName != null) {
                        return roleName.toString();
                    }
                }
                
                // 从请求头获取角色名称（需要URL解码）
                String roleNameHeader = request.getHeader("X-Role-Name");
                if (roleNameHeader != null && !roleNameHeader.isEmpty()) {
                    try {
                        return URLDecoder.decode(roleNameHeader, StandardCharsets.UTF_8);
                    } catch (Exception e) {
                        return roleNameHeader; // 如果解码失败，返回原值
                    }
                }
            }
            
            // 默认返回空
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}